//
//  NvEditVideoViewController.m
//  NvSellerShow
//
//  Created by dx on 17/2/7.
//  Copyright © 2017年 Meicam. All rights reserved.
//

#import "NvEditVideoViewController.h"
#import "NvTextViewWithCancelButton.h"
#import "NvsVideoClip.h"
#import "NvsTimelineCaption.h"
#import "NvPlaySlider.h"
#import <Photos/Photos.h>
#import "NvStickerTemplateCollectionViewCell.h"
#import "NvsThumbnailSequenceView.h"
#import "NvAssetManager.h"
#import "PPNumberButton.h"



@interface NvEditVideoViewController () <NvsStreamingContextDelegate,SAVideoRangeSliderDelegate>
{
    BOOL _isPlaying;
    BOOL _hasAddedCaption;
    BOOL _isCaptionChanged;
    NvsVideoTrack *_videoTrack;
    NSTimer *_playbackProgressTimer;
    NSMutableArray *_stickerArray;
    NSIndexPath *_selectedIndexPath;
    
    NSNumber* _audioVolumn;
}
@property (weak, nonatomic) IBOutlet UIView *titleView;
@property (weak, nonatomic) IBOutlet UIButton *finishBtn;
@property (weak, nonatomic) IBOutlet UIView *addCaptionView;
@property (weak, nonatomic) IBOutlet UIView *editVideoView;
@property (weak, nonatomic) IBOutlet UIView *addWaterMarkView;
@property (weak, nonatomic) IBOutlet NvTextViewWithCancelButton *captionTextView;
@property (weak, nonatomic) IBOutlet UIButton *horiBtn;
@property (weak, nonatomic) IBOutlet UIButton *vertBtn;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NvPlaySlider *sliderProgress;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *livewindow16x9AspectConstriant;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *livewindow1x1AspectConstriant;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerVerticalConstraint;



@property (weak, nonatomic) IBOutlet NSLayoutConstraint *waterMarkControlHConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *waterMarkCollectionViewHConstraint;

@property (weak, nonatomic) IBOutlet NvsThumbnailSequenceView *thumbnailSequence;
@property (weak, nonatomic) IBOutlet UIView *detailVideoEditView;
@property (weak, nonatomic) IBOutlet UIView *mainImageEditView;
@property (weak, nonatomic) IBOutlet PPNumberButton *imageEditBtn;
@property (weak, nonatomic) IBOutlet NvPlaySlider *audioSlider;
@property (weak, nonatomic) IBOutlet UILabel *audioVolumnLabel;

@property (weak, nonatomic) IBOutlet UIView *playControlView;
@property (nonatomic, strong) UIButton *play_Pause;

@end

@implementation NvEditVideoViewController
{
    CGFloat _sequencein;
    CGFloat _sequenceout;
    BOOL isShow;//是否显示控制栏标志
    NSTimer *timer;//控制控制栏的隐藏与显示
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _isPlaying = false;
    _isCaptionChanged = false;
    _sliderProgress.value = 0 ;
    _captionTextView.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewDidChange) name:UITextViewTextDidChangeNotification object:nil];
    
    [self fitLiveWindowHeight];
    [self SetUpUI];
    
    if(_editMode == AddWaterMark)
    {
        [self buildTimeLineForSticker];
    }
    else if(_editMode == EditVideo)
    {
        [self buildTimeLineForEdit];
    }
    else if(_editMode == AddCaption)
    {
        [self buildTimeLineForCaption];
    }
    [self.streamingContext connectTimeline:self.timeline withLiveWindow:self.liveWindow];
    self.streamingContext.delegate = self;

    [self seekTimeline];
    self.editSlider.delegate = self;
    
    //注册通知,监听键盘出现
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(keyboardWillShow:)
                                                name:UIKeyboardWillShowNotification
                                              object:nil];
    //注册通知，监听键盘消失事件
    [[NSNotificationCenter defaultCenter]addObserver:self
                                            selector:@selector(keyboardWillHide:)
                                                name:UIKeyboardWillHideNotification
                                              object:nil];
    
    
    [self.liveWindow addSubview:self.play_Pause];
    [self.play_Pause mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@52);
        make.centerX.equalTo(self.liveWindow.mas_centerX);
        make.centerY.equalTo(self.liveWindow.mas_centerY);
    }];
//    isShow = YES;
//    [self addGestureRecognizer];
//    [self startTimer];
}

//给liveWindow添加手势
- (void)addGestureRecognizer {
    [self.liveWindow addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gestureRecognizer)]];
}

- (void)gestureRecognizer {
    if (isShow) {
        [self hidenControlView];
    } else {
        [self showControlView];
    }
}

//创建定时器隐藏控制栏
- (void)startTimer {
    timer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(timerClick) userInfo:nil repeats:NO];
    
    timer = [NSTimer timerWithTimeInterval:4 target:self selector:@selector(timerClick) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
}

- (void)timerClick {
    if (isShow) {
        [self hidenControlView];
    }
}

//显示控制栏
- (void)showControlView {
    isShow = YES;
    [timer invalidate];
    [UIView animateWithDuration:0.3 animations:^{
        self.playControlView.top_LL -= 44;
    } completion:^(BOOL finished) {
        [self startTimer];
    }];
}
//隐藏控制栏
- (void)hidenControlView {
    isShow = NO;
    [timer invalidate];
    [UIView animateWithDuration:0.3 animations:^{
        self.playControlView.top_LL += 44;
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self drawUIBezierPath];
}

- (void)drawUIBezierPath {
    
    if(_finishBtn.layer.mask != nil)
        return;
    UIBezierPath *topfieldPath = [UIBezierPath bezierPathWithRoundedRect:_titleView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(2 , 2)];
    UIBezierPath *bottomFieldPath = [UIBezierPath bezierPathWithRoundedRect:_finishBtn.bounds byRoundingCorners:UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii:CGSizeMake(2 , 2)];
    
    CAShapeLayer *ffieldLayer = [[CAShapeLayer alloc] init];
    CAShapeLayer *afieldLayer = [[CAShapeLayer alloc] init];
    
    ffieldLayer.frame = _finishBtn.bounds;
    ffieldLayer.path = bottomFieldPath.CGPath;
    afieldLayer.frame = _titleView.bounds;
    afieldLayer.path = topfieldPath.CGPath;
    
    _finishBtn.layer.mask = ffieldLayer;
    _titleView.layer.mask = afieldLayer;
}

- (void)fitLiveWindowHeight {
    if(self.createMode == NvSSVideoCreateScaleSquare){
        self.livewindow16x9AspectConstriant.active = NO;
        [self.view addConstraint:self.livewindow1x1AspectConstriant];
    }
}


///键盘显示事件
- (void) keyboardWillShow:(NSNotification *)notification {
    //获取键盘高度，在不同设备上，以及中英文下是不同的
    CGFloat kbHeight = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
    CGFloat offset = (_addCaptionView.top_LL+_addCaptionView.height_LL) - (self.view.height_LL - kbHeight);
    
    // 取得键盘的动画时间，这样可以在视图上移的时候更连贯
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    //将视图上移计算好的偏移
    if(offset > 0) {
        [UIView animateWithDuration:duration animations:^{
            self.containerVerticalConstraint.constant -= offset;
        }];
    }
}


//hide the keyboard when click other area
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    if (![touch.view isKindOfClass: [UITextField class]] || ![touch.view isKindOfClass: [UITextView class]]) {
        [self.view endEditing:YES];
    }
}

///键盘消失事件
- (void) keyboardWillHide:(NSNotification *)notify {
    // 键盘动画时间
    double duration = [[notify.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    //视图下沉恢复原状
    [UIView animateWithDuration:duration animations:^{
        self.containerVerticalConstraint.constant = 0;
    }];
}

-(void) buildTimeLineForCaption
{
    [self buildNewTimeLine];
    if(_clipModel.clipType ==  NvClipImage){
        if(_clipModel.imageDuration.intValue != 0)
            [_videoTrack appendClip:_clipModel.clipPath trimIn:0 trimOut:_clipModel.imageDuration.intValue * NS_TIME_BASE];
        else
            [_videoTrack appendClip:_clipModel.clipPath trimIn:0 trimOut:4 * NS_TIME_BASE];
        
    }else if (_clipModel.clipType ==  NvClipVideo) {
        if((_clipModel.triminTimeStamp.longLongValue == 0 && _clipModel.trimoutTimeStamp.longLongValue == 0))
            [_videoTrack appendClip:_clipModel.clipPath];
        else
            [_videoTrack appendClip:_clipModel.clipPath trimIn:_clipModel.triminTimeStamp.longLongValue trimOut:_clipModel.trimoutTimeStamp.longLongValue];
    }
    
    if(_clipModel.clipCaption.length != 0)
    {
        self.captionTextView.text = _clipModel.clipCaption;
        [self addCaption];
    }
    if(self.themeUuid) {
        [self.timeline applyTheme:self.themeUuid];
        NvsVideoClip *clip = [self getFirstGeneralClipFromVideoTrack:_videoTrack];
        _sequencein = clip.inPoint;
        _sequenceout = clip.outPoint;
        self.durationLabel.text = [Utils stringWithTime:(_sequenceout-_sequencein)/NS_TIME_BASE];
    }
    else
        self.durationLabel.text = [Utils stringWithTime:_timeline.duration/NS_TIME_BASE];

    self.curLabel.text = [Utils stringWithTime:0];
    
}

-(void) buildTimeLineForEdit
{
    [self buildNewTimeLine];
    NvsClip *clip = nil;
    if(_clipModel.clipType ==  NvClipImage){
        if(_clipModel.imageDuration.intValue != 0)
            clip = [_videoTrack appendClip:_clipModel.clipPath trimIn:0 trimOut:_clipModel.imageDuration.intValue * NS_TIME_BASE];
        else
            clip = [_videoTrack appendClip:_clipModel.clipPath trimIn:0 trimOut:4 * NS_TIME_BASE];
        
    }else if (_clipModel.clipType ==  NvClipVideo) {
        [_videoTrack appendClip:_clipModel.clipPath];
    }
    
    if(_clipModel.audioVolumn.floatValue == -1)
    {
        _audioVolumn = [NSNumber numberWithFloat:1];
    }
    else
    {
        _audioVolumn = _clipModel.audioVolumn;
    }
    //初始化数据trimoutTimestamp，triminTimestamp，audioVolumn
    if(_createMode == NvSSVideoCreateScaleHorizontal)
    {
        self.detailVideoEditView.hidden = NO;
        self.mainImageEditView.hidden = YES;
        self.thumbnailSequence.stillImageHint = NO;
        self.thumbnailSequence.mediaFilePath = _clipModel.clipPath;
        self.thumbnailSequence.startTime = 0;
        self.thumbnailSequence.duration = _timeline.duration;

        if(_clipModel.trimoutTimeStamp.longLongValue == 0)
        {
            _clipModel.trimoutTimeStamp = [NSNumber numberWithLongLong: self.timeline.duration];
        }
        
        self.editSlider.durationSeconds = _timeline.duration;
        _triminTimestamp = _clipModel.triminTimeStamp;
        _trimoutTimestamp = _clipModel.trimoutTimeStamp;
        self.editSlider.minGap = self.triminTimestamp;
        self.editSlider.maxGap = self.trimoutTimestamp;
        _audioSlider.value = _audioVolumn.floatValue;
        _sliderProgress.value = self.editSlider.minGap.longLongValue*1.0/self.timeline.duration;
    }
    else
    {
        self.detailVideoEditView.hidden = YES;
        self.mainImageEditView.hidden = NO;
        self.imageEditBtn.minValue = 1;
        self.imageEditBtn.maxValue = 15;
        self.imageEditBtn.textColor = [UIColor whiteColor];
        self.imageEditBtn.inputFieldFont = 23;
        self.imageEditBtn.backgroundColor = [UIColor colorWithHexString:@"#313A46"];
        if(_clipModel.imageDuration.intValue != 0)
            self.imageEditBtn.currentNumber = _clipModel.imageDuration.intValue;
        else
            self.imageEditBtn.currentNumber = 4;
        self.imageEditBtn.shakeAnimation = YES;
        self.imageEditBtn.resultBlock = ^(NSString *num){
            int time = [num intValue];
            [self resetImageDuration:time];
        };
        
    }
    [clip setVolumeGain:_audioVolumn.floatValue rightVolumeGain:_audioVolumn.floatValue];
    _audioSlider.value = _audioVolumn.floatValue;
    _audioVolumnLabel.text = [self stringWithFloat:_audioVolumn.floatValue];
    
    self.curLabel.text = [Utils stringWithTime:_clipModel.triminTimeStamp.longLongValue/NS_TIME_BASE];
    self.durationLabel.text = [Utils stringWithTime:_timeline.duration/NS_TIME_BASE];

}

-(void) buildTimeLineForSticker
{
    [self useBaseTimeLine];
    self.curLabel.text = [Utils stringWithTime:0];
    self.durationLabel.text = [Utils stringWithTime:_timeline.duration/NS_TIME_BASE];

}

-(void) useBaseTimeLine
{
    [self registerStickerCollectionViewCell];
    [self initStickerArray];
}

-(void) buildNewTimeLine
{
    _timeline = [Utils createTimeLine:_editMode];
    _videoTrack = [_timeline appendVideoTrack];
}

-(void)resetImageDuration:(int) time
{
    if(_isPlaying)
    {
        [self.streamingContext stop];
        _isPlaying = false;
        [self.playButton setImage:[self imageFromBundle:@"player_play"]  forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
        _sliderProgress.value = 0;
    }
    self.durationLabel.text = [Utils stringWithTime:time];
}

- (void) SetUpUI
{
    if(_editMode == AddCaption)
    {
        self.addCaptionView.hidden = NO;
        self.editVideoView.hidden = YES;
        self.addWaterMarkView.hidden = YES;
        self.titleImageView.image = [self imageFromBundle:@"switch_text"];
        self.titleLabel.text = @"添加说明";
        
        self.captionInputHconstraint.constant += 44;
        self.captionControlHConstraint.constant = 0;
    }
    else if(_editMode == EditVideo)
    {
        self.addCaptionView.hidden = YES;
        self.editVideoView.hidden = NO;
        self.addWaterMarkView.hidden = YES;
        self.titleImageView.image = [self imageFromBundle:@"switch_edit"];
        self.titleLabel.text = @"编辑片段";
    }
    else if(_editMode == AddWaterMark)
    {
        self.addCaptionView.hidden = YES;
        self.editVideoView.hidden = YES;
        self.addWaterMarkView.hidden = NO;
        self.titleImageView.image = [self imageFromBundle:@"make_mark"];
        self.titleLabel.text = @"选择一个水印";
        self.waterMarkCollectionViewHConstraint.constant += self.waterMarkControlHConstraint.constant;
        self.waterMarkControlHConstraint.constant = 0;
    }
}

-(void)addCaption
{
    if (_hasAddedCaption)
    {
        NvsTimelineCaption *caption = [self getFirstGeneralCaption:self.timeline];
        if(caption)
            [self.timeline removeCaption:caption];

        _hasAddedCaption = false;
    }
    
    NvsVideoClip *videoClip = [self getFirstGeneralClipFromVideoTrack:_videoTrack];
    if(videoClip) {
        NSString *captionStylePackageId = nil;
        if([self.timeline getCurrentThemeId])
            captionStylePackageId = @"theme";
        [_timeline addCaption:_captionTextView.text inPoint:videoClip.inPoint duration:videoClip.outPoint - videoClip.inPoint captionStylePackageId:captionStylePackageId];
        _hasAddedCaption = true;
    }
}

- (NvsTimelineCaption *)getFirstGeneralCaption:(NvsTimeline *)timeline {
    NvsTimelineCaption *caption = nil;
    NvsTimelineCaption *tempCaption = [timeline getFirstCaption];
    while (tempCaption) {
        if (tempCaption.roleInTheme == NvsRoleInThemeGeneral)
        {
            caption = tempCaption;
            break;
        }
        else
            tempCaption = [_timeline getNextCaption:tempCaption];
    }
    return caption;
}

- (NvsVideoClip *)getFirstGeneralClipFromVideoTrack:(NvsVideoTrack *)track {
    NvsVideoClip *videoClip = nil;
    for (unsigned int i = 0; i < track.clipCount; i++)
    {
        NvsVideoClip *tempClip = [track getClipWithIndex:i];
        if (tempClip.roleInTheme != NvsRoleInThemeGeneral)
            continue;
        videoClip = tempClip;
        break;
    }
    return videoClip;
}

- (void)addSticker{
    //remove current sticker
    NvsTimelineAnimatedSticker *sticker = [_timeline getFirstAnimatedSticker];
    if(sticker != nil)
        [_timeline removeAnimatedSticker:sticker];
    
    //none sticker
    if(_stickerPackageId == nil || [_stickerPackageId isEqualToString:@""]) {
        //do nothing
    }
    else {
        [_timeline addAnimatedSticker:0 duration:_timeline.duration animatedStickerPackageId:_stickerPackageId];
    }
    [self seekTimeline];
}

- (void)seekTimeline {
    if (_isPlaying) {
        _isPlaying = false;
        [_playbackProgressTimer invalidate];
    }
    if(_editMode == AddCaption && self.themeUuid)
        [self.streamingContext seekTimeline:_timeline timestamp:lround((self.sliderProgress.value * (_sequenceout - _sequencein))+_sequencein) videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
    else
        [self.streamingContext seekTimeline:_timeline timestamp:lround(self.sliderProgress.value * _timeline.duration) videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
       
}

- (IBAction)playback:(id)sender {
    if (_isPlaying) {//暂停
        [timer invalidate];
        self.play_Pause.hidden = NO;
        
        [self.streamingContext stop];
        _isPlaying = false;
        [self.playButton setImage:[self imageFromBundle:@"player_play"]  forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
    } else {//播放
        
        [self startTimer];
        self.play_Pause.hidden = YES;
        
        if(_isCaptionChanged)
        {
            [self addCaption];
            [self seekTimeline];
             _isCaptionChanged = false;
        }
        if(_editMode == EditVideo && _createMode == NvSSVideoCreateScaleSquare && _imageDuration.intValue!= _imageEditBtn.currentNumber)
        {
            [_videoTrack removeAllClips];
            _imageDuration = [NSNumber numberWithInteger:_imageEditBtn.currentNumber];
            [_videoTrack appendClip:_clipModel.clipPath trimIn:0 trimOut:_imageDuration.intValue * NS_TIME_BASE];
        }
        
        int64_t startTime = self.sliderProgress.value * _timeline.duration;
        int64_t endTime = _timeline.duration;
        if(self.editSlider.maxGap > 0 && _editMode == EditVideo) {
            if(startTime < self.triminTimestamp.longLongValue || startTime >= self.trimoutTimestamp.longLongValue)
                startTime = self.triminTimestamp.longLongValue;
            endTime = self.trimoutTimestamp.longLongValue;
        }
        if(_editMode == AddCaption && self.themeUuid)
        {
            startTime = _sequencein + (_sequenceout - _sequencein) * self.sliderProgress.value;
            endTime = _sequenceout;
        }
        [self.streamingContext playbackTimeline:_timeline startTime:startTime endTime:endTime videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize preload:YES flags:0];
        
        NSTimeInterval timeInterval = 0.1;
        _playbackProgressTimer = [NSTimer timerWithTimeInterval:timeInterval target:self selector:@selector(handleProgressTimer:) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop]addTimer:_playbackProgressTimer forMode:NSRunLoopCommonModes];
        
        [self.playButton setImage:[self imageFromBundle:@"player_stop"]  forState:UIControlStateNormal];
        _isPlaying = true;
        
    }
}

- (void)handleProgressTimer:(NSTimer *)timer {
    if(_editMode == AddCaption && self.themeUuid)
        self.sliderProgress.value = self.sliderProgress.maximumValue * ([self.streamingContext getTimelineCurrentPosition:_timeline]-_sequencein)/(_sequenceout - _sequencein);
    else
        self.sliderProgress.value = self.sliderProgress.maximumValue * ([self.streamingContext getTimelineCurrentPosition:_timeline])/ (_timeline.duration);
    [self updateLabel];
}

- (void) updateLabel {
    if(_editMode == AddCaption && self.themeUuid)
        self.curLabel.text = [Utils stringWithTime: self.sliderProgress.value * (_sequenceout-_sequencein)/NS_TIME_BASE];
    else
        self.curLabel.text = [Utils stringWithTime: self.sliderProgress.value * _timeline.duration/NS_TIME_BASE];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (IBAction)closeBtnPressed:(id)sender {
    [self.streamingContext stop];
    if(_editMode == AddCaption)
    {
        [self clearTimeLine];
    }
    self.streamingContext.delegate = nil;
    [self dismissViewControllerAnimated:YES completion:nil];
}



- (IBAction)sliderValueChanged:(id)sender {
    [self updateLabel];
    [self seekTimeline];
}

- (void)textViewDidChange {
    if(_isPlaying)
    {
        [self.streamingContext stop];
        _isPlaying = false;
        [self.playButton setImage:[self imageFromBundle:@"player_play"]  forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
    }
    _isCaptionChanged = true;
}

- (void)didPlaybackEOF:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        
        self.play_Pause.hidden = NO;
        [timer invalidate];
        
        _isPlaying = false;
        [self.playButton setImage:[self imageFromBundle:@"player_play"] forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
        self.sliderProgress.value = _editSlider.minGap.longLongValue/_timeline.duration;
        [self updateLabel];
    }
}

- (void)didPlaybackStopped:(NvsTimeline *)timeline {
    if(timeline == self.timeline) {
        _isPlaying = false;
        [self.playButton setImage:[self imageFromBundle:@"player_play"] forState:UIControlStateNormal];
        [_playbackProgressTimer invalidate];
    }
}
- (IBAction)finishBtnPressed:(id)sender {
    self.streamingContext.delegate = nil;
    [self dismissViewControllerAnimated:NO completion:^(){
        [self.streamingContext stop];
        if(_editMode == AddCaption)
        {
            [self clearTimeLine];
            if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSetCaption:)] ==YES) {
                [self.delegate didFinishSetCaption:_captionTextView.text];
            }
        }
        else if(_editMode == AddWaterMark)
        {
            if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSetSticker:)] ==YES) {
                [self.delegate didFinishSetSticker:_stickerPackageId];
            }

        }
        else if(_editMode == EditVideo)
        {
            if(_createMode == NvSSVideoCreateScaleHorizontal)
            {
                if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSetVideoTrimIn:andTrimOut:sound:)] ==YES) {
                    [self.delegate didFinishSetVideoTrimIn:_triminTimestamp andTrimOut:_trimoutTimestamp sound:_audioVolumn];
                }
            }
            else
            {
                if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didFinishSetImageDuration:sound:)] ==YES) {
                    [self.delegate didFinishSetImageDuration:[NSNumber numberWithInteger:_imageEditBtn.currentNumber] sound:_audioVolumn];
                }
            }
        }
    }];
}

-(void) clearTimeLine
{
    if (_timeline)
        [self.streamingContext removeTimeline:_timeline];
    self.streamingContext = nil;

}
#pragma mark - SliderDelegate
- (void)videoRange:(SAVideoRangeSlider *)videoRange didChangeLeftPosition:(CGFloat)leftPosition rightPosition:(CGFloat)rightPosition {
    _triminTimestamp = [NSNumber numberWithLongLong:leftPosition];
    _trimoutTimestamp = [NSNumber numberWithLongLong:rightPosition];
    _sliderProgress.value = leftPosition/(_timeline.duration);
    NSLog(@"%f-----%f",leftPosition,rightPosition);
    
    float timestamp;
    if(videoRange.isLeft) {
        _curLabel.text = [Utils stringWithTime:leftPosition/NS_TIME_BASE];
        timestamp = leftPosition;
    } else {
        timestamp = rightPosition;
    }
    [self startSeekTimeline:timestamp];
}

#pragma mark - Theme Area TableView
- (void)registerStickerCollectionViewCell {
    static NSString* stickerCellIdentifier = @"NvStickerTemplateCollectionViewCell";
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    [self.collectionView registerNib:[UINib nibWithNibName:@"NvStickerTemplateCollectionViewCell" bundle:myBundle]  forCellWithReuseIdentifier:stickerCellIdentifier];
}

#pragma mark - Utility Methods

- (void)borderIsSelected:(BOOL)selected forView:(NvStickerTemplateCollectionViewCell *)cell {
    cell.radiusView.border = (selected) ? 2 : 0;
}

- (NvStickerTemplateCollectionViewCell *)cellAtIndexPath:(NSIndexPath *)indexPath {
    return (NvStickerTemplateCollectionViewCell*)[self.collectionView cellForItemAtIndexPath:indexPath];
}


#pragma mark <UICollectionViewDataSource>

//返回section中的cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _stickerArray.count;
}

//返回cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* themeCellIdentifier = @"NvStickerTemplateCollectionViewCell";
    NvStickerTemplateCollectionViewCell* stickerCell = [self.collectionView dequeueReusableCellWithReuseIdentifier:themeCellIdentifier forIndexPath:indexPath];
    
    NvAssetModel *model = _stickerArray[indexPath.row];

    BOOL isSelected = _selectedIndexPath ? ([_selectedIndexPath compare:indexPath] == NSOrderedSame) : NO;
    [self borderIsSelected:isSelected forView:stickerCell];
    UIImage *thumb;
    if([model.assetId isEqualToString:@""]) {
        thumb = [self imageFromBundle:@"sticker_none"];
        stickerCell.radiusView.imageView.contentMode = UIViewContentModeCenter;
    }
    else {
        thumb = [UIImage imageWithContentsOfFile:model.imageCoverPath];
        stickerCell.radiusView.imageView.contentMode = UIViewContentModeScaleToFill;
    }
    
    stickerCell.radiusView.image = thumb;
    
    [stickerCell.radiusView makeImageRadius: 0];

    return stickerCell;
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if([_selectedIndexPath isEqual:indexPath])
        return;
    
    if(_selectedIndexPath){
        [self borderIsSelected:NO forView:[self cellAtIndexPath:_selectedIndexPath]];
    }
    _selectedIndexPath = indexPath;
    [self borderIsSelected:YES forView:[self cellAtIndexPath:indexPath]];
    [self installCurrentStricker];
    [self addSticker];
   
    
}

- (void)initStickerArray {
    _stickerArray = [NSMutableArray array];
    //add null sticker
    NvAssetModel * noneStickerModel = [[NvAssetModel alloc] initWithPath:@"" andId:@"" andType:NvAssetAnimatedSticker];
    [_stickerArray addObject:noneStickerModel];
    
    if(_createMode == NvSSVideoCreateScaleHorizontal){
        [_stickerArray addObjectsFromArray:[[NvAssetManager new] getAssetsWithAssetType:NvAssetAnimatedSticker]];
    }
    else {
        [_stickerArray addObjectsFromArray:[[NvAssetManager new] getAssetsWithAssetType:NvAssetAnimatedSticker]];
    }
    
    //to do: set curent sticker
    if(self.stickerPackageId == nil)
        _selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    else {
        NvAssetModel *stickerModel;
        for (NSInteger i = 0; i < _stickerArray.count; i++) {
            stickerModel = _stickerArray[i];
            if([_stickerPackageId isEqualToString:stickerModel.assetId] == YES) {
                _selectedIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                break;
            }
        }
    }

}


- (void) startSeekTimeline:(float)timestamp{
    [self.streamingContext seekTimeline:self.timeline timestamp:timestamp videoSizeMode:NvsVideoPreviewSizeModeLiveWindowSize flags:0];
}
/**
 *  将时间转化为合适的字符串
 *
 */

- (NvAssetModel *)getStickerModelWithIndexPath:(NSIndexPath *)indexPath {
    return (NvAssetModel *)_stickerArray[indexPath.row];
}

- (void)installCurrentStricker {
    NvAssetModel * waitingInstallModel = [self getStickerModelWithIndexPath:_selectedIndexPath];
    if([waitingInstallModel.assetId isEqualToString:@""] == YES) {
        _stickerPackageId = @"";
        return;
    }
    
    NvsAssetPackageManagerError  error;
    NSString *intallingStickerPackagePath = waitingInstallModel.assetPackagePath;
    NSString * waitingInstallPackageId = waitingInstallModel.assetId;
    
    NvsAssetPackageStatus packageStatus = [self.streamingContext.assetPackageManager getAssetPackageStatus:waitingInstallPackageId type:(NvsAssetPackageType)waitingInstallModel.type];
    
    //package is already installed
    if(packageStatus != NvsAssetPackageStatus_NotInstalled) {
        NSInteger installedVersion = [self.streamingContext.assetPackageManager getAssetPackageVersion:waitingInstallPackageId type:(NvsAssetPackageType)waitingInstallModel.type];
        //package need to update
        if(waitingInstallModel.version > installedVersion) {
            error = [self.streamingContext.assetPackageManager upgradeAssetPackage:intallingStickerPackagePath license:nil type:(NvsAssetPackageType)waitingInstallModel.type sync:YES assetPackageId:_stickerPackageId];
        }
        else {
            _stickerPackageId = waitingInstallPackageId;
        }
    }
    //package need install
    else {
        error = [self.streamingContext.assetPackageManager installAssetPackage: intallingStickerPackagePath license:nil type:(NvsAssetPackageType)waitingInstallModel.type sync:YES assetPackageId:_stickerPackageId];
    }
    
    if(error == NvsAssetPackageManagerError_NoError|| error == NvsAssetPackageManagerError_AlreadyInstalled)
        _stickerPackageId = [self getStickerModelWithIndexPath:_selectedIndexPath].assetId;
    NSLog(@"installing sticker Package: %d %@ \n %@ \n %@", error, intallingStickerPackagePath, _stickerPackageId, [self getStickerModelWithIndexPath:_selectedIndexPath].assetId);
}
- (IBAction)audioSliderValueChanged:(id)sender {
     _audioVolumn = [NSNumber numberWithFloat:_audioSlider.value];
    _audioVolumnLabel.text = [self stringWithFloat:_audioVolumn.floatValue];
    
    NvsVideoClip *tempClip = [_videoTrack getClipWithIndex:0];
    [tempClip setVolumeGain:_audioVolumn.floatValue rightVolumeGain:_audioVolumn.floatValue];
}

- (NSString *)stringWithFloat:(float)volume
{
    return [NSString stringWithFormat:@"%.f%%",volume*100];
}
//MARK: Getter
- (UIButton *)play_Pause {
    if (!_play_Pause) {
        _play_Pause = [UIButton buttonWithType:UIButtonTypeCustom];
        [_play_Pause setImage:[self imageFromBundle:@"player_preview"] forState:UIControlStateNormal];
        [_play_Pause addTarget:self action:@selector(playback:) forControlEvents:UIControlEventTouchUpInside];
//        _play_Pause.hidden = YES;
    }
    return _play_Pause;
}
//MARK:dealloc
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (UIImage *)imageFromBundle:(NSString*)imageName {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"NvSellerResource" ofType:@"bundle"];
    NSBundle *myBundle = [NSBundle bundleWithPath:path];
    NSString *imagePath = [myBundle pathForResource:imageName ofType:@"png"];
    UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
    return image;
}
@end
